package logic

import (
	"context"
	"encoding/xml"
	"fmt"

	"laundry-service/app/client/internal/svc"
	"laundry-service/app/client/internal/types"
	"laundry-service/entity"

	"github.com/zeromicro/go-zero/core/logx"
)

type ExpressSignNtfCallbackLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewExpressSignNtfCallbackLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ExpressSignNtfCallbackLogic {
	return &ExpressSignNtfCallbackLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ExpressSignNtfCallbackLogic) ExpressSignNtfCallback(req *types.WkStNtfReq) (resp []byte, err error) {
	var expressSignNtfReq entity.ExpressSignNtfReq

	if err := xml.Unmarshal([]byte(req.Pkg), &expressSignNtfReq); err != nil {
		fmt.Printf("xml.Unmarshal error: %v\n", err)
	}

	// 根据快递单号查询订单
	order, err := l.svcCtx.Db.GetOrderBySFBillCode(expressSignNtfReq.WaybillNo)
	if err != nil {
		logx.Errorf("查询订单失败，请求体参数: %v, 错误: %v", expressSignNtfReq, err)
		return nil, nil
	}

	bagLogList, err := l.svcCtx.Db.GetBagLogListByOrderId(order.ID)
	if err != nil {
		logx.Errorf("查询包裹日志失败，订单ID: %v, 错误: %v", order.ID, err)
		return nil, nil
	}

	// 是否是送回签收
	isBackSign := false

	for _, bagLog := range bagLogList {
		// 如果存State大于等于5的状态 说明此次签收通知为商品寄回签收
		if bagLog.State >= 5 {
			isBackSign = true
			return nil, nil
		}
	}

	orderLog := entity.NewStateLogWithOrder(order, 2, expressSignNtfReq.OrderStatus, req.Pkg)
	if !isBackSign {
		// 如果是寄回签收
		orderLog.State = 1
		orderLog.Remark = "工厂已签收"

		order.State = 2
		err = l.svcCtx.Db.SaveOrder(order)
		if err != nil {
			logx.Errorf("保存订单失败，订单ID: %d, 错误: %v", order.ID, err)
		}
	}

	// // 提交事务
	if err := l.svcCtx.Db.TxExpressSignNtfCallback(order, orderLog); err != nil {
		logx.Errorf("ExpressSignNtfCallback error: %v", err)
		return nil, nil
	}

	bin, _ := xml.MarshalIndent(&SFReply{Head: "OK"}, "", "  ")
	return bin, nil
}
